package com.ltedu.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ltedu.auth.client.AuthClient;
import com.ltedu.auth.vo.LoginUser;
import com.ltedu.common.contants.Constants;
import com.ltedu.common.dto.UserDTO;
import com.ltedu.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @className: UserDetailsServiceImpl
 * @auther: Jerry
 * @date: 2020/11/27 19:58
 * @desctiption: TODO
 * @version: 1.0
 */
@Service("userService")
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private AuthClient authClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //将来连接数据库根据账号查询用户信息
        Result result = authClient.info(username);
        if(result == null || result.getCode() != Constants.SUCCESS){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
//        System.out.println("result:" + result.getData());
        UserDTO userDTO = JSONObject.parseObject(JSON.toJSONString(result.getData()), UserDTO.class);
        return new LoginUser(userDTO);
    }
}
